<template>
  <page-content left>
    <div>
      <h1>{{ parent.slug }} {{ parent.name }}</h1>
      <space class="my-1 header-actions">
        <loading-action :action="onSaveOrder">保存</loading-action>
        <a-button @click="onReset">重置</a-button>
        <a-button @click="createDialog = true">添加虚拟字段</a-button>
        <doc-preview
          :label="`列表页字段总览`"
          :title="`列表页字段总览`"
          :content="listFields"
        />
        <doc-preview
          :label="`详情页字段总览`"
          :title="`详情页字段总览`"
          :content="detailFields"
        />
        <doc-preview
          :label="`搜索栏字段总览`"
          :title="`搜索栏字段总览`"
          :content="searchFields"
        />
        <doc-preview
          :label="`表单页字段总览`"
          :title="`表单页字段总览`"
          :content="formFields"
        />
      </space>
      <a-divider orientation="right" :dashed="true">
        列表页--搜索栏--详情页--表单页
      </a-divider>
      <nested-draggable
        ref="routers"
        :expand-keys="defaultExpanded"
        class="system-models"
        :list="systemModels"
        :children="false"
        handle=".drag"
      >
        <template #default="{ data }">
          <div class="item-wrap">
            <children-field :data="data"/>
          </div>
          <div class="flex-spacer"/>
          <space style="min-width: 60px;">
            <!-- 列表页 -->
            <a-switch 
            checked-children="隐藏" 
            un-checked-children="显示" 
            v-model="data.list_hide"
            />
          </space>
          <space style="min-width: 60px;">
            <!-- 搜索栏 -->
            <a-switch 
            checked-children="隐藏" 
            un-checked-children="显示" 
            v-model="data.search_hide"
            />
          </space>
          <space style="min-width: 60px;">
            <!-- 详情页 -->
            <a-switch 
            checked-children="隐藏" 
            un-checked-children="显示" 
            v-model="data.detail_hide"
            />
          </space>
          <space v-if="!data.is_virtual" style="min-width: 60px;">
            <!-- 表单页 -->
            <a-switch 
            checked-children="隐藏" 
            un-checked-children="显示" 
            v-model="data.form_hide"
            />
          </space>
          <space v-if="!data.is_virtual">
            <router-link target='_blank' :to="`/system-models/${data.parent_id}/edit?id=${data.id}`">编辑</router-link>
          </space>
          <space v-if="data.is_virtual" style="min-width: 88px;">
            <router-link target='_blank' :to="`/system-models/${data.id}/edit`">编辑</router-link>
            <lz-popconfirm v-if="data.is_virtual" :confirm="onDestroy(data)" title="删除该虚拟字段">
              <a class="error-color" href="javascript:void(0);">删除</a>
            </lz-popconfirm>
          </space>
        </template>
      </nested-draggable>
    </div>
    <a-modal
      title="添加虚拟字段"
      v-model="createDialog"
      :footer="null"
      width="600px"
    >
    <lz-form
      ref="form"
      :form.sync="form"
      :errors.sync="errors"
      :submit="onSubmit"
      in-dialog
      layout="vertical"
      :redirectDetail="false"
      :redirectList="false"
      :pass_delete="false"
    >
      <lz-form-item 
        label="虚拟字段标识" 
        prop="slug" 
        required
      >
        <a-input v-model="form.slug" type="input"/>
      </lz-form-item>
      <lz-form-item 
        label="虚拟字段名称" 
        prop="name" 
        required
      >
        <a-input v-model="form.name" type="input"/>
      </lz-form-item>
      <lz-form-item 
        label="默认值" 
        prop="value"
        :tip="`显示的默认值`"
      >
        <a-input v-model="form.value" type="input"/>
      </lz-form-item>
      <lz-form-item 
          label="列表页是否隐藏" 
          prop="list_hide"
          :style="this.inLine20"
        >
          <a-switch v-model="form.list_hide"/>
        </lz-form-item>
        <lz-form-item 
          label="详情页是否隐藏" 
          prop="detail_hide"
          :style="this.inLine20"
        >
          <a-switch v-model="form.detail_hide"/>
        </lz-form-item>
        <lz-form-item 
          label="列表页宽度" 
          prop="list_width"
          :style="this.inLine20"
        >
          <a-select v-model="form.list_width">
            <a-select-option key="50">50</a-select-option>
            <a-select-option key="100">100</a-select-option>
            <a-select-option key="150">150</a-select-option>
            <a-select-option key="200">200</a-select-option>
          </a-select>
        </lz-form-item>
        <lz-form-item 
          label="列表页固定" 
          prop="list_fixed"
          :style="this.inLine20"
        >
          <a-select v-model="form.list_fixed">
            <a-select-option :key="null">不固定</a-select-option>
            <a-select-option key="left">左侧</a-select-option>
            <a-select-option key="right">右侧</a-select-option>
          </a-select>
        </lz-form-item>
    </lz-form>
    </a-modal>
  </page-content>
</template>

<script>
import {
  storeSystemModel,
  getSystemModelsField,
  updateSystemModelField,
  updateSystemModel,
  destroySystemModel
} from '@/api/system-models'
import LzPopconfirm from '@c/LzPopconfirm'
import {
  getMessage,
  hasChildren,
  removeFromNested,
  changeListDefault,
} from '@/libs/utils'
import NestedDraggable from '@c/NestedDraggable'
import Space from '@c/Space'
import PageContent from '@c/PageContent'
import LoadingAction from '@c/LoadingAction'
import LzForm from '@c/LzForm/index'
import LzFormItem from '@c/LzForm/LzFormItem'
import _forIn from 'lodash/forIn'
import DocPreview from '@c/DocPreview'
import ChildrenField from './ChildrenField'

export default {
  name: 'Field',
  scroll: true,
  components: {
    Space,
    NestedDraggable,
    LzPopconfirm,
    PageContent,
    LoadingAction,
    LzFormItem,
    LzForm,
    DocPreview,
    ChildrenField
  },
  data() {
    return {
      systemModels: [],
      parent: {},
      systemModelsBak: '',
      listFields: [],
      searchFields: [],
      formFields: [],
      detailFields: [],
      // 默认展开第二级模型
      defaultExpanded: [],
      createDialog: false,
      form: {
        name: '',
        slug: '',
        type: 'input',
        list_hide: false,
        search_hide: true,
        form_hide: true,
        detail_hide: false,
        is_virtual: true,
        parent_id: this.$route.params.id,
        list_width: 150,
        list_fixed: null,
      },
      inLine20: {
        display: 'inline-block',
        width: '20%'
      },
      errors: {},
    }
  },
  created() {
    this.getSystemModelsField(this.$route.params.id)
  },
  activated() {
    // 缓存的页面，由于不会执行 created 方法，所以滚动行为，放在该钩子里
    this.$scrollResolve()
  },
  methods: {
    async getSystemModelsField() {
      const { data: { 
        list, 
        parent, 
        listFields,
        searchFields, 
        formFields,
        detailFields, 
      } } = await getSystemModelsField(this.$route.params.id)
      this.systemModels = changeListDefault(list)
      
      this.listFields = '<pre>'+JSON.stringify(listFields, null, 4)+'</pre>'
      this.searchFields = '<pre>'+JSON.stringify(searchFields, null, 4)+'</pre>'
      this.formFields = '<pre>'+JSON.stringify(formFields, null, 4)+'</pre>'
      this.detailFields = '<pre>'+JSON.stringify(detailFields, null, 4)+'</pre>'
      this.parent = parent
      this.systemModelsBak = JSON.stringify(this.systemModels)
      this.defaultExpanded = this.systemModels.filter(i => hasChildren(i)).map(i => i.id)

      this.$scrollResolve()
    },
    hasChildren,
    /**
     * 获取模型结构，仅包含 id 和 children 字段
     * @param systemModels
     * @returns {Array}
     */
    getSystemModelStruct(systemModels = this.systemModels) {
      const struct = []
      systemModels.forEach((i) => {
        struct.push({
          id: i.id,
          list_hide: i.list_hide,
          search_hide: i.search_hide,
          form_hide: i.form_hide,
          detail_hide: i.detail_hide,
          children: hasChildren(i)
            ? this.getSystemModelStruct(i.children)
            : undefined,
        })
      })
      return struct
    },
    async onSaveOrder() {
      await updateSystemModelField({
        _order: this.getSystemModelStruct(this.systemModels),
      },this.$route.params.id)
      this.$message.success(getMessage('updated'))
    },
    onReset() {
      this.systemModels = JSON.parse(this.systemModelsBak)
      this.$message.info('已重置修改，记得保存')
    },
    async onSubmit($form) {
      const { data } = await storeSystemModel(this.form)
      this.systemModels.unshift(data)
      if ($form.stay) {
        $form.onReset()
      } else {
        this.createDialog = false
      }
    },
    onDestroy(row) {
      return async () => {
        await destroySystemModel(row.id)
        this.$message.success(getMessage('destroyed'))
        removeFromNested(this.systemModels, row.id)
      }
    },
    updateSystemModel
  },
}
</script>

<style scoped lang="less">
@import "~@/styles/vars";

.system-models {
  width: 1100px;

  .id {
    width: 200px;
    display: inline-block;
    text-align: center;
    font-weight: bolder;
  }

  .item-wrap {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.header-actions {
  width: 100%;
  overflow-x: auto;
}
</style>
